package com.heima.behavior.service.impl;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApCollectionBehaviorService;
import com.heima.model.behavior.dtos.CollectionBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
public class ApCollectionBehaviorServiceImpl implements ApCollectionBehaviorService {

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public ResponseResult collectBehavior(CollectionBehaviorDTO dto) {
        //1检验参数  文章ID不能为空  使用注解
        //拿到user对象
        Integer userId = AppThreadLocalUtils.getUser().getId();
        //2调用查询行为实体方法
        //获取设备ID
        Integer equipmentId = dto.getEquipmentId();
        //根据用户ID和设备ID获取当前     实体行为对象
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, equipmentId);
        //3如果是收藏   0 收藏 1 取消收藏
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(apBehaviorEntry.getId()));
        ApCollection apCollection = mongoTemplate.findOne(query, ApCollection.class);

        if (apCollection == null && dto.getOperation() == 0) {
            //如果没有收藏，而且当前用户行为是收藏
            ApCollection apCollection1 = new ApCollection();
            apCollection1.setEntryId(apBehaviorEntry.getId());
            apCollection1.setArticleId(dto.getArticleId());
            apCollection1.setCreatedTime(new Date());
            ApCollection result = mongoTemplate.save(apCollection1);
            return ResponseResult.okResult(result);
        } else {
            //取消不喜欢
            DeleteResult result = mongoTemplate.remove(query, ApCollection.class);
            return ResponseResult.okResult(result);
        }
    }


}
